/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.tomcat.util.net;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.net.NioEndpoint.Poller;
import org.apache.tomcat.util.res.StringManager;

/**
 * Base class for a SocketChannel wrapper used by the endpoint. This way, logic for an SSL socket
 * channel remains the same as for a non SSL, making sure we don't need to code for any exception
 * cases.
 *
 * @version 1.0
 */
public class NioChannel implements ByteChannel {

    private static final Log log = LogFactory.getLog(NioChannel.class);
    protected static final StringManager sm = StringManager.getManager(NioChannel.class);

    protected static final ByteBuffer emptyBuf = ByteBuffer.allocate(0);

    protected SocketChannel socketChannel;
    protected SocketWrapperBase<NioChannel> socketWrapper = null;

    protected final SocketBufferHandler bufHandler;

    protected Poller poller;

    public NioChannel(SocketChannel channel, SocketBufferHandler bufHandler) {
        this.socketChannel = channel;
        this.bufHandler = bufHandler;
        log.info("NioChannel constructor. " + channel);
    }

    /**
     * Reset the channel
     *
     * @throws IOException If a problem was encountered resetting the channel
     */
    public void reset() throws IOException {
        bufHandler.reset();
    }


    void setSocketWrapper(SocketWrapperBase<NioChannel> socketWrapper) {
        this.socketWrapper = socketWrapper;
    }

    /**
     * Free the channel memory
     */
    public void free() {
        bufHandler.free();
    }

    /**
     * Returns true if the network buffer has been flushed out and is empty.
     *
     * @param block Unused. May be used when overridden
     * @param s Unused. May be used when overridden
     * @param timeout Unused. May be used when overridden
     * @return Always returns <code>true</code> since there is no network buffer in the regular
     * channel
     * @throws IOException Never for non-secure channel
     */
    public boolean flush(boolean block, Selector s, long timeout) throws IOException {
        return true;
    }


    /**
     * Closes this channel.
     *
     * @throws IOException If an I/O error occurs
     */
    @Override
    public void close() throws IOException {
        getIOChannel().socket().close();
        getIOChannel().close();
    }

    /**
     * Close the connection.
     *
     * @param force Should the underlying socket be forcibly closed?
     * @throws IOException If closing the secure channel fails.
     */
    public void close(boolean force) throws IOException {
        if (isOpen() || force) {
            close();
        }
    }

    /**
     * Tells whether or not this channel is open.
     *
     * @return <code>true</code> if, and only if, this channel is open
     */
    @Override
    public boolean isOpen() {
        return socketChannel.isOpen();
    }

    @Override
    public int write(ByteBuffer src) throws IOException {
        checkInterruptStatus();
        final String content = new String(src.array(), src.position(), src.remaining(), StandardCharsets.ISO_8859_1);
        final int cnt = socketChannel.write(src);
        log.info("向SocketChannel写入字节数 " + cnt + " -->\n" + content + "<--");
        return cnt;
    }

    @Override
    public int read(ByteBuffer dst) throws IOException {
        final int cnt = socketChannel.read(dst);
        log.info("从SocketChannel中读取到字节数 " + cnt); // 详细内容打印在后面
        return cnt;
    }

    public Object getAttachment() {
        Poller pol = getPoller();
        Selector sel = pol != null ? pol.getSelector() : null;
        SelectionKey key = sel != null ? getIOChannel().keyFor(sel) : null;
        return key != null ? key.attachment() : null;
    }

    public SocketBufferHandler getBufHandler() {
        return bufHandler;
    }

    public Poller getPoller() {
        return poller;
    }

    public SocketChannel getIOChannel() {
        return socketChannel;
    }

    public boolean isClosing() {
        return false;
    }

    public boolean isHandshakeComplete() {
        return true;
    }

    /**
     * Performs SSL handshake hence is a no-op for the non-secure implementation.
     *
     * @param read Unused in non-secure implementation
     * @param write Unused in non-secure implementation
     * @return Always returns zero
     * @throws IOException Never for non-secure channel
     */
    public int handshake(boolean read, boolean write) throws IOException {
        return 0;
    }

    public void setPoller(Poller poller) {
        this.poller = poller;
    }

    public void setIOChannel(SocketChannel IOChannel) {
        this.socketChannel = IOChannel;
    }

    @Override
    public String toString() {
        return super.toString() + ":" + this.socketChannel.toString();
    }

    public int getOutboundRemaining() {
        return 0;
    }

    /**
     * Return true if the buffer wrote data. NO-OP for non-secure channel.
     *
     * @return Always returns {@code false} for non-secure channel
     * @throws IOException Never for non-secure channel
     */
    public boolean flushOutbound() throws IOException {
        return false;
    }

    protected void checkInterruptStatus() throws IOException {
        if (Thread.interrupted()) {
            throw new IOException(sm.getString("channel.nio.interrupted"));
        }
    }


    private ApplicationBufferHandler appReadBufHandler;

    public void setAppReadBufHandler(ApplicationBufferHandler handler) {
        this.appReadBufHandler = handler;
    }

    protected ApplicationBufferHandler getAppReadBufHandler() {
        return appReadBufHandler;
    }
}
